//
//  EDDepositActionViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/9.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDDepositActionViewController.h"
#import "TPKeyboardAvoidingScrollView.h"
#import "PayPalModel.h"
#import "DepositStatusViewController.h"
#import "HelpDepositViewController.h"
#import "LLWebViewController.h"
#import "UIButton+WebCache.h"
@interface EDDepositActionViewController ()

@property(nonatomic,strong)NSMutableArray *titleButtons;
@property(nonatomic,strong)NSMutableArray *wayArray;
@property(nonatomic,strong)NSMutableArray *wayButtons;
@property(nonatomic,strong)NSMutableArray *priceButtons;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UIImageView *chooseImage;
@property(nonatomic,strong)NSArray *priceArrray;
@property(nonatomic,strong)UIView *paypalView;
@property(nonatomic,strong)UIView *priceView;
@property(nonatomic,strong)UIButton *depositBtn;
@property(nonatomic,strong)UIButton *helpdepositBtn;
@property(nonatomic,strong)NSString* amount;
@property(nonatomic,strong)NSString* bank_id;
@property(nonatomic,strong)UITextField * maxField;
@property(nonatomic,strong)NSString* pay_url;
@property(nonatomic,assign)NSInteger pay_urlGoType; //外链还是内链
@property(nonatomic,strong)NSString* page_min_amount; //最低
@property(nonatomic,strong)NSString* page_max_amount; //最高
@end

@implementation EDDepositActionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WHITECOLOR;
    self.titleButtons = [NSMutableArray new];
    [self setpUI];
    [self getPassageway];
    _helpdepositBtn.hidden = YES;
}
-(void)setpUI{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, kStatusBarAndNavigationBarHeight, UIScreenWidth, UIScreenHeight - kStatusBarAndNavigationBarHeight)];
    _scrollView.backgroundColor = RGBA(245, 245, 245, 1);
    [self.view addSubview:_scrollView];
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, 50)];
    view.backgroundColor= WHITECOLOR;
    [_scrollView addSubview:view];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(RealValue_H(40), 17, 16, 16)];
    imageView.image = [UIImage imageNamed:@"btn_Chose_Sel"];
    [view addSubview:imageView];
    UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(imageView.right +8, 0, 200, 30)];
    lable.textColor = MAINCOLOR;
    lable.font = AutoFont(14);
    lable.text = _modell.name;
    lable.centerY = imageView.centerY;
    [view addSubview:lable];
    
    _paypalView = [[UIView alloc] initWithFrame:CGRectMake(0,224, UIScreenWidth, 0)];
    _paypalView.backgroundColor = WHITECOLOR;
    [_scrollView addSubview:_paypalView];
    NSArray * titles =@[@"立即存款",@"帮我存款"];
    for (int i =0; i<titles.count; i++)
    {
        UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenWidth/2 -RealValue_H(250), UIScreenHeight - 157 + i*(RealValue_H(100)+20), RealValue_H(500), RealValue_H(88))];
        
        [button setTitleColor:WHITECOLOR forState:0];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag =i;
        [button setTitle:titles[i] forState:0];
        button.titleLabel.font = AutoFont(16);
        KViewRadius(button, 4);
        [self.view addSubview:button];
        if (i ==0) {
            _depositBtn = button;
        }else
        {
            _helpdepositBtn =button;
        }
    }
    [self loginButtonNormalStatus];
    _priceView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 0)];
    _priceView.backgroundColor = WHITECOLOR;
    [_scrollView addSubview:_priceView];
  
   
}
- (void)loginButtonHighLightStatus
{
    _depositBtn.userInteractionEnabled = YES;//恢复点击
    [_depositBtn setBackgroundImage:[UIImage imageNamed:@"tab active"] forState:0];
    _depositBtn.backgroundColor = WHITECOLOR;
    _helpdepositBtn.userInteractionEnabled = YES;//恢复点击
    [_helpdepositBtn setBackgroundImage:[UIImage imageNamed:@"tab active"] forState:0];
    _depositBtn.backgroundColor = WHITECOLOR;
}
- (void)loginButtonNormalStatus
{
    _depositBtn.userInteractionEnabled = NO;//恢复点击
    [_depositBtn setBackgroundImage:[UIImage imageNamed:@""] forState:0];
    _depositBtn.backgroundColor = ColorStr(@"A1A1A1");
    _helpdepositBtn.userInteractionEnabled = NO;//恢复点击
    [_helpdepositBtn setBackgroundImage:[UIImage imageNamed:@""] forState:0];
    _helpdepositBtn.backgroundColor = ColorStr(@"A1A1A1");
}
- (void)buttonClick:(UIButton *)sender
{
    switch (sender.tag) {
        case 0: //立即存款
        {
          
            WeakSelf
            [self showLoadingAnimation];
            NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"submitDeposit"];
            NSString * no = [WJUnit getarc4random];
            NSDictionary * parameters = @{@"promotion_id":_modell.id,
                                          @"no":no,
                                          @"amount":_amount,
                                          @"bank_id":_bank_id,
                                          @"attachcode":no};
            [[SmileHttpTool sharedInstance] GET :AllGame parameters:parameters origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
                NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
                 [self stopLoadingAnimation];
                if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                    NSString * str =kFormat(@"%@&qrcodeOrderId=%@&qrcodeAmount=%@", weakSelf.pay_url,no,weakSelf.amount);
                    if (weakSelf.pay_urlGoType ==2) {
                      
                       
                        dispatch_async(dispatch_get_main_queue(), ^{
                           // UI更新代码
                           [self open_UrlHandle:str];
                        });
                    }else{
                        
                        LLWebViewController * webview = [[LLWebViewController alloc] init];
                        webview.urlStr = str;
                        webview.isType = 1;
                        webview.titleStr = @"存款";
                        webview.isWebGo = self.isWebGo;
                        [self.navigationController pushViewController:webview animated:YES];
                                        
                    }
                
                    
                }else{
                    
                    DepositStatusViewController * DepositstatusVC = [[DepositStatusViewController alloc] init];
                    DepositstatusVC.title = @"存款信息";
                    [weakSelf.navigationController pushViewController:DepositstatusVC animated:YES];
                    [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                }
                
                
            } failure:^(id responseObject, NSError *error) {
                 [self stopLoadingAnimation];
                
            }];
        }
            
          
            
            break;
        case 1: //帮我存款
            
        {
            NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"moneyMobileAction"];
            WeakSelf
            [self showLoadingAnimation];
            [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
                NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
                if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
                    NSArray * activeDeposit = dict[@"data"][@"activeDeposit"];
                    if (activeDeposit.count>0)
                    {
                        DepositStatusViewController * DepositstatusVC = [[DepositStatusViewController alloc] init];
                        DepositstatusVC.title = @"存款信息";
                        [weakSelf.navigationController pushViewController:DepositstatusVC animated:YES];
                        [JMNotifyView showNotify:@"有未完成存款"  isSuccessful:NO];
                    }else
                    {
                        NSString * no = [WJUnit getarc4random];
                        NSString * str =kFormat(@"%@&qrcodeOrderId=%@&qrcodeAmount=%@", weakSelf.pay_url,no,weakSelf.amount);
                        HelpDepositViewController * HelpDepositVC = [[HelpDepositViewController alloc] init];
                        HelpDepositVC.title = @"帮我存款";
                        HelpDepositVC.urlStr =str;
                        HelpDepositVC.amontStr = weakSelf.amount;
                        [self.navigationController pushViewController:HelpDepositVC animated:YES];
//                        http://119.81.171.98/tongyaSubmit?para=ylsm&qrcodeOrderId=CK1563464999735112&qrcodeAmount=100
                    }
                    
                }else{
                    
                    [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
                }
                [self stopLoadingAnimation];
                
            } failure:^(id responseObject, NSError *error) {
                
                [self stopLoadingAnimation];
            }];
        }
            break;
        default:
            break;
    }
}
- (void)choosePaypalWithIndex:(NSInteger)index
{
    
    PayModel * Pay = self.wayArray[index];
    [self addButtonWithGameArray:Pay.channel_list];
    for (UIButton *button in _titleButtons) {
        if (button.tag == index) {
            button.layer.borderWidth       =1;
            button.layer.borderColor       =[MAINCOLOR CGColor];
            self.chooseImage.mj_x = button.right-10;
            self.chooseImage.mj_y = button.mj_y -6;
            
        }else{
            button.layer.borderWidth       =0;
            button.layer.borderColor       =[WHITECOLOR CGColor];
        }
    }
}
- (void)paypal:(UIButton *)sender
{
    [self choosePaypalWithIndex:sender.tag];
}
- (void)getPassageway
{
    [self showLoadingAnimation];
    WeakSelf
    NSString  * AllGame = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"getUserInfoPay"];
    [[SmileHttpTool sharedInstance] GET :AllGame parameters:@{} origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        NSDictionary * dict = [WJUnit dictionaryWithJsonString:responseObject];
        if ([[dict jsonString:@"statusCode"] isEqualToString:@"SUCCESS"]) {
            NSDictionary * dic = [self objectFromJSONString:responseObject];
            weakSelf.wayArray  = [PayModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
            
            for (int i=0; i< weakSelf.wayArray.count; i++)
            {
                PayModel * model = weakSelf.wayArray[i];
                NSInteger index = i % 4;
                NSInteger page = i / 4;
                
                UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(RealValue_H(40)+ index * (RealValue_H(140) + RealValue_H(36)), page  * (64 + 10)+15 +50, RealValue_H(140), 64)];
                [button addTarget:self action:@selector(paypal:) forControlEvents:UIControlEventTouchUpInside];
                button.tag = i;
                UIImageView * imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, button.mj_y + 10, 54/2, 20)];
                imageV.centerX = button.centerX;
                imageV.contentMode =  UIViewContentModeScaleAspectFit;
                [imageV sd_setImageWithURL:[NSURL URLWithString:model.img_url]];
                UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(0, imageV.bottom+4, button.width, 20)];
                lable.centerX = button.centerX;
                lable.text = model.name;
                lable.font = AutoFont(12);
                lable.textColor = BLACKCOLOR;
                lable.textAlignment = NSTextAlignmentCenter;
                [weakSelf.titleButtons addObject:button];
                [weakSelf.scrollView addSubview:button];
                [weakSelf.scrollView addSubview:imageV];
                [weakSelf.scrollView addSubview:lable];
                button.backgroundColor = WHITECOLOR;
                KViewRadius(button, 2);
                if (i == weakSelf.wayArray.count-1)
                {
                    weakSelf.chooseImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, -100, 16, 16)];
                    weakSelf.chooseImage.image = [UIImage imageNamed:@"PayPalchoose"];
                    [weakSelf.scrollView addSubview:weakSelf.chooseImage];
                    weakSelf.paypalView.mj_y = button.bottom +10;
                    
                }
                if ([model.suggest isEqualToString:@"是"]) {
                    UIImageView * icon = [[UIImageView alloc] initWithFrame:CGRectMake(button.mj_x, button.mj_y, 29, 35)];
                    icon.image = [UIImage imageNamed:@"gametuijian"];
                    icon.tag=100;
                    [weakSelf.scrollView addSubview:icon];
                }
            }
            
            [self choosePaypalWithIndex:0];
           
            
        }else{
            [JMNotifyView showNotify:[dict jsonString:@"message"]  isSuccessful:NO];
        }
        [self stopLoadingAnimation];
        
    } failure:^(id responseObject, NSError *error) {
        
        
    }];
}
//循环创建Button
-(UIView *)addButtonWithGameArray:(NSArray *)arr{
    
    for (UIView *view in self.paypalView.subviews) {
        if (view.tag>=1000) {
            [view removeFromSuperview];
        }
        
    }
    _priceArrray = arr;
    CGFloat h = 0;
    UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 120, 20)];
    lable.textColor = RGBA(68, 68, 68, 1);
    lable.text = @"选择通道:";
    lable.font = AutoFont(14);
    lable.tag =2000;
    [_paypalView addSubview:lable];
    
    self.wayButtons = [NSMutableArray new];
   
    for (int i = 0; i < arr.count; i++) {
        PayClassModel * model = _priceArrray[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [_wayButtons addObject:button];
        [button addTarget:self action:@selector(payClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag =1000 + i;
        [button setBackgroundColor:RGBA(244, 244, 244, 1) forState:UIControlStateNormal];
        [button setBackgroundColor:RGBA(190, 227, 255, 1) forState:UIControlStateSelected];
        [button setTitleColor:RGBA(91, 91, 91, 1) forState:UIControlStateNormal];
        [button setTitleColor:MAINCOLOR forState:UIControlStateSelected];
        button.titleLabel.font = AutoFont(14);
        KViewRadius(button, 2);
        //为button赋值
        [button setTitle:model.typename forState:UIControlStateNormal];

        NSInteger index = i % 4;
        NSInteger page = i / 4;
       
        button.frame = CGRectMake(12+ index * (80 + 8), page  * (36 + 10)+lable.bottom+10, 80, 36);//重设button的frame
        [_paypalView addSubview:button];
        h = 46 *(page+1);
        if ([model.suggest isEqualToString:@"是"]) {
            UIImageView * icon = [[UIImageView alloc] initWithFrame:CGRectMake(button.mj_x, button.mj_y, 29, 35)];
            icon.image = [UIImage imageNamed:@"gametuijian"];
            icon.tag=1000;
            [_paypalView addSubview:icon];
        }
        
    }
    
    _paypalView.height = h +50;
    if (_priceArrray.count>0) {
         [self getPriceWithIndex:1000];
    }
   
    return _paypalView;

}
// 通道入口
- (void)payClick:(UIButton *)sender
{
    [self getPriceWithIndex:sender.tag];
}
- (void)getPriceWithIndex:(NSInteger)index
{
    for (UIButton *button in _wayButtons) {
        if (button.tag == index) {
           
            button.selected = YES;
        }else{
           button.selected = NO;
        }
    }
   PayClassModel * model = _priceArrray[index-1000];
    _bank_id = model.bank_id;
    _pay_url = model.pay_url;
    _pay_urlGoType = [model.open_type integerValue];
    if ([model.allow_helppay isEqualToString:@"是"])
    {
        _helpdepositBtn.hidden = NO;
    }else
    {
         _helpdepositBtn.hidden = YES;
    }
    for (UIView *view in _scrollView.subviews) {
        if (view.tag==10086) {
            [view removeFromSuperview];
        }
        
    }
    
    
   [self addButtonWithPriceArray:model];
    _amount = @"0";
    [self loginButtonNormalStatus];
    
  if (!kStringIsEmpty(model.page_tips)) {
     UILabel * messageLable = [[UILabel alloc] initWithFrame:CGRectMake(10, _paypalView.bottom +5, UIScreenWidth-20, 0)];
        messageLable.tag  =10086;
        messageLable.numberOfLines = 0;
        messageLable.font = AutoFont(12);
        NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[model.page_tips dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
        messageLable.attributedText = attrStr;
        [messageLable sizeToFit];
        messageLable.width = 320;
        messageLable.height = messageLable.height +4;
        messageLable.textColor = MAINCOLOR;
        [_scrollView addSubview:messageLable];
       _priceView.mj_y = _paypalView.bottom +messageLable.height+10;
      
  }else
  {
       _priceView.mj_y = _paypalView.bottom +10;
  }
   
   
    //设置scrollView 滚动
    [self.scrollView setContentSize:CGSizeMake(UIScreenWidth, _priceView.height + _paypalView.height +167 +100 +187)];
    //隐藏滚动条
    self.scrollView.showsVerticalScrollIndicator = NO;
}
//循环创建Button
-(UIView *)addButtonWithPriceArray:(PayClassModel *)model{
    
    for (UIView *view in self.priceView.subviews) {
        if (view.tag>1000) {
            [view removeFromSuperview];
        }
        
    }
    NSArray *array = [ model.page_quck_amount componentsSeparatedByString:@","]; //从字符A中分隔成2个元素的数组
    CGFloat h = 0;
    UILabel * lable = [[UILabel alloc] initWithFrame:CGRectMake(12, 12, 120, 20)];
    lable.textColor = RGBA(68, 68, 68, 1);
    lable.text = @"存款金额(元):";
    lable.font = AutoFont(14);
    lable.tag =2000;
    [_priceView addSubview:lable];
    
    _maxField = [[UITextField alloc] initWithFrame:CGRectMake(12, lable.bottom+8, 350, 44)];
    _maxField.textColor = RGBA(61, 61, 61, 1);
    _page_min_amount = model.page_min_amount;
    _page_max_amount = model.page_max_amount;
    _maxField.placeholder = kFormat(@"单笔最低%@元，最高%@元", _page_min_amount,_page_max_amount);
    _maxField.font = AutoFont(16);
    _maxField.tintColor = RGBA(61, 61, 61, 1);
    _maxField.backgroundColor = RGBA(241, 241, 241, 1);
    _maxField.tag =2001;
    _maxField.textAlignment = NSTextAlignmentCenter;
     _maxField.keyboardType = UIKeyboardTypeDecimalPad;
    [_maxField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_priceView addSubview:_maxField];
    
    UILabel * mesageLable = [[UILabel alloc] initWithFrame:CGRectMake(12, _maxField.bottom+8, 350, 20)];
    mesageLable.textColor = RGBA(161, 161, 161, 1);
    
    mesageLable.font = AutoFont(14);
    NSString * message;
    if (_isEqual)
    {
        message = kFormat(@"*该活动的存款金额必须等于 %@",_price);
    }else
    {
       message = (_price.integerValue ==0)?kFormat(@"*该活动的存款金额必须大于 %@",_price) : kFormat(@"*该活动的存款金额必须大于或等于 %@",_price);
    }
   
    mesageLable.attributedText = [WJUnit finderattributedString:message attributedString:_price color:MAINCOLOR font:AutoFont(14)];
    mesageLable.tag =2002;
    [_priceView addSubview:mesageLable];
    
    self.priceButtons = [NSMutableArray new];
    for (int i = 0; i < array.count; i++) {
        NSString * price = array[i];
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        [button addTarget:self action:@selector(priceClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag =3000 + i;
        [button setBackgroundColor:RGBA(244, 244, 244, 1) forState:UIControlStateNormal];
         [button setBackgroundColor:RGBA(190, 227, 255, 1) forState:UIControlStateSelected];
        [button setTitleColor:RGBA(91, 91, 91, 1) forState:UIControlStateNormal];
        [button setTitleColor:MAINCOLOR forState:UIControlStateSelected];
        button.titleLabel.font = AutoFont(14);
        KViewRadius(button, 2);
        [self.priceButtons addObject:button];
        //为button赋值
        [button setTitle:price forState:UIControlStateNormal];
        
        NSInteger index = i % 4;
        NSInteger page = i / 4;
        
        button.frame = CGRectMake(12+ index * (80 + 8), page  * (36 + 10)+mesageLable.bottom+10, 80, 36);//重设button的frame
        [_priceView addSubview:button];
       
        if (i==array.count-1) {
            
            NSInteger count = array.count % 4;
            if (count==0) {
                 h = page *36 + 36;
            }else
            {
                h = (page+1) *36+10;
            }
        }
    }
    _priceView.height = h + 120+20;
    
    return _priceView;
    
}
-(void)textFieldDidChange :(UITextField *)TextField{
   
    
    [self price:TextField.text];
   
}
- (void)price:(NSString *)price
{
    
    
    if (_isEqual)
    {
        if (price.floatValue ==_price.floatValue)
        {
            _amount =  price;
            [self loginButtonHighLightStatus];
        }else
        {
            [self loginButtonNormalStatus];
        }
    }else
    {
        if (price.floatValue >= _page_min_amount.floatValue && price.floatValue<=_page_max_amount.floatValue)
        {
             _amount =  price;
            if (_amount.floatValue >=_price.floatValue) {
 
                [self loginButtonHighLightStatus];
                
            }else
            {
                [self loginButtonNormalStatus];
            }
        }else
        {
            [self loginButtonNormalStatus];
        }
        
    }
}
- (void)priceClick:(UIButton *)sender
{    
    for (UIButton *button in _priceButtons) {
        if (button.tag == sender.tag) {
            
            button.selected = YES;
        }else{
            button.selected = NO;
        }
    }
    _maxField.text = sender.currentTitle;
    [self price:sender.currentTitle];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

-(void)open_UrlHandle:(NSString *)url{
    
    
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:url]])
           {
               
               if (@available(iOS 10.0, *)) {
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
               } else {
                   // Fallback on earlier versions
               }
           }else
           {
               if (@available(iOS 10.0, *)) {
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];
               } else {
                   // Fallback on earlier versions
               }
           }
    
}

@end
